import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:wms/utils/utils.dart';
import '../../services/api_service.dart';
import 'package:provider/provider.dart';
import '../../services/auth_service.dart';
import 'package:flutter/services.dart';
import '/models/putaway_summary_response.dart';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';
import '../../utils/rangeInput_formatter.dart';

class PutawayTasksScreen extends StatefulWidget {
  final Map<String, dynamic> jsonData;
  const PutawayTasksScreen({super.key, required this.jsonData});

  @override
  _PutawayTasksScreenState createState() => _PutawayTasksScreenState();
}

class _PutawayTasksScreenState extends State<PutawayTasksScreen> with WidgetsBindingObserver {
  final _itemNumberController = TextEditingController();
  final _lpnController = TextEditingController();
  final _qtyController = TextEditingController();
  final _locationController = TextEditingController();
  
  // 焦点控制（新增：初始禁用输入框的键盘触发）
  final FocusNode _itemFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _lpnFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _qtyFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _locationFocusNode = FocusNode(canRequestFocus: true);

  // 输入框键盘状态（默认全部收起）
  bool _locationKeyboardVisible = false;
  bool _itemKeyboardVisible = false;
  bool _lpnKeyboardVisible = false;
  bool _qtyKeyboardVisible = false;
  String? _currentFocusField; // 记录当前聚焦的输入框

  String? itemNumber;
  String? internalItemNumber;
  String? lpnNumber;
  String? packKey;
  String? orderNumber;
  
  bool _scannedData = false;
  var helpText = '';

  late int? loadId;
  String? loadNumber;
  late int? warehouseId;
  late int? userId;
  late String totalAdded = '0';
  String? totalQuantity;
  int? orderId;
  late PutawaySummaryResponse responseData;
  bool hideNextButton = true;
  String? oldItemNumber;
  bool _isLoading = false;
  int? remainingQty;

  late double _fontScale;
  late double labelFontSize = 13;
  late double textFontSize = 12;
  late double buttonFontSize = 14;
  late double errorFontSize = 13;

  // 底部按钮区域总高度
  static const double _bottomButtonAreaHeight = 140;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    
    loadId = widget.jsonData['loadId'];
    loadNumber = widget.jsonData['loadNumber'];
    print('load id ---$loadId');
    print('load number ---$loadNumber');
    
    // 初始化焦点监听（仅跟踪焦点，不自动弹键盘）
    _initFocusListeners();
    
    // 关键修复1：页面加载后，先强制隐藏键盘，再聚焦Location（阻断系统默认唤起）
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (mounted) {
        // 第一步：强制隐藏键盘（覆盖系统默认行为）
        await _hideKeyboard();
        // 第二步：聚焦Location输入框（此时键盘已被隐藏，不会唤起）
        _focusOnField('location', showKeyboard: false);
      }
    });
  }

  // 初始化焦点监听（移除自动弹键盘逻辑，新增焦点变化时强制隐藏键盘）
  void _initFocusListeners() {
    _locationFocusNode.addListener(() {
      _handleFocusChange('location', _locationFocusNode);
      // 修复：焦点变化时若未主动触发键盘，强制隐藏
      if (_locationFocusNode.hasFocus && !_locationKeyboardVisible) {
        _hideKeyboard();
      }
    });
    _itemFocusNode.addListener(() {
      _handleFocusChange('item', _itemFocusNode);
      if (_itemFocusNode.hasFocus && !_itemKeyboardVisible) {
        _hideKeyboard();
      }
    });
    _lpnFocusNode.addListener(() {
      _handleFocusChange('lpn', _lpnFocusNode);
      if (_lpnFocusNode.hasFocus && !_lpnKeyboardVisible) {
        _hideKeyboard();
      }
    });
    _qtyFocusNode.addListener(() {
      _handleFocusChange('qty', _qtyFocusNode);
      if (_qtyFocusNode.hasFocus && !_qtyKeyboardVisible) {
        _hideKeyboard();
      }
    });
  }

  // 应用后台返回前台时重置所有键盘
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
    }
  }

  // 处理焦点变化（仅跟踪焦点状态，不自动弹键盘）
  void _handleFocusChange(String field, FocusNode node) {
    if (node.hasFocus) {
      // 获得焦点：仅记录当前聚焦字段，不弹键盘
      if (_currentFocusField != null && _currentFocusField != field) {
        _hideKeyboardForField(_currentFocusField!);
      }
      _setCurrentFocusField(field);
    } else {
      // 失去焦点：关闭对应键盘
      if (_currentFocusField == field) {
        _hideKeyboardForField(field);
        _currentFocusField = null;
      }
    }
  }

  // 设置当前聚焦的输入框
  void _setCurrentFocusField(String field) {
    setState(() {
      _currentFocusField = field;
    });
  }

  // 关键修复2：增强键盘隐藏方法，确保执行成功（增加延迟重试）
  Future<void> _showKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.show');
    } catch (e) {
      print('显示键盘失败: $e');
    }
  }

  Future<void> _hideKeyboard() async {
    try {
    // 第一次尝试隐藏
    await SystemChannels.textInput.invokeMethod('TextInput.hide');
    // 延迟50ms再次隐藏（防止系统延迟唤起）
    await Future.delayed(const Duration(milliseconds: 50));
    await SystemChannels.textInput.invokeMethod('TextInput.hide');
    
    // 关键修复：同步当前聚焦字段的状态为false（确保图标显示正确）
    if (mounted && _currentFocusField != null) {
      setState(() {
        _updateKeyboardState(_currentFocusField!, false);
      });
    }
  } catch (e) {
    print('隐藏键盘失败: $e');
    // 异常时再次重试
    await Future.delayed(const Duration(milliseconds: 100));
    await SystemChannels.textInput.invokeMethod('TextInput.hide');
    // 异常后仍同步状态
    if (mounted && _currentFocusField != null) {
      setState(() {
        _updateKeyboardState(_currentFocusField!, false);
      });
    }
  }
  }

  // 显示指定输入框的键盘（同步状态）
  void _showKeyboardForField(String field) {
    setState(() {
      _updateKeyboardState(field, true);
    });
    _showKeyboard();
  }

  // 隐藏指定输入框的键盘（同步状态）
  void _hideKeyboardForField(String field) {
    setState(() {
      _updateKeyboardState(field, false);
    });
    _hideKeyboard();
  }

  // 切换指定输入框的键盘状态（点击键盘图标时调用）
  void _toggleKeyboardForField(String field) {
    bool currentState = _getKeyboardState(field);
    // 关键修复：先更新状态，再执行显示/隐藏操作（确保状态优先同步）
    setState(() {
      _updateKeyboardState(field, !currentState);
    });
    
    if (currentState) {
      // 当前显示：隐藏键盘 + 失焦
      _hideKeyboard();
      _unfocusField(field);
    } else {
      // 当前隐藏：聚焦 + 显示键盘
      _focusOnField(field, showKeyboard: true);
    }
  }

  // 关键修复3：优化聚焦方法，移除延迟（避免聚焦后系统延迟唤起键盘）
  void _focusOnField(String field, {required bool showKeyboard}) {
    // 先取消所有焦点，避免冲突
    FocusScope.of(context).unfocus();
    // 移除延迟：立即聚焦（防止系统在延迟期间唤起键盘）
    if (mounted) {
      switch (field) {
        case 'location':
          FocusScope.of(context).requestFocus(_locationFocusNode);
          break;
        case 'item':
          FocusScope.of(context).requestFocus(_itemFocusNode);
          break;
        case 'lpn':
          FocusScope.of(context).requestFocus(_lpnFocusNode);
          break;
        case 'qty':
          FocusScope.of(context).requestFocus(_qtyFocusNode);
          break;
      }
      // 只有明确要求时才弹键盘（仅点击输入框/键盘图标时触发）
      if (showKeyboard) {
        _showKeyboardForField(field);
        // 容错：若弹键盘失败，同步重置状态
        _showKeyboard().then((_) {
          if (mounted && !_getKeyboardState(field)) {
            _hideKeyboardForField(field);
          }
        });
      } else {
        // 修复：即使不弹键盘，也强制隐藏一次（防止系统默认唤起）
        _hideKeyboard();
      }
    }
  }

  // 取消指定输入框的焦点
  void _unfocusField(String field) {
    switch (field) {
      case 'location':
        _locationFocusNode.unfocus();
        break;
      case 'item':
        _itemFocusNode.unfocus();
        break;
      case 'lpn':
        _lpnFocusNode.unfocus();
        break;
      case 'qty':
        _qtyFocusNode.unfocus();
        break;
    }
  }

  // 获取指定输入框的键盘状态
  bool _getKeyboardState(String field) {
    switch (field) {
      case 'location':
        return _locationKeyboardVisible;
      case 'item':
        return _itemKeyboardVisible;
      case 'lpn':
        return _lpnKeyboardVisible;
      case 'qty':
        return _qtyKeyboardVisible;
      default:
        return false;
    }
  }

  // 更新指定输入框的键盘状态
  void _updateKeyboardState(String field, bool visible) {
    setState(() {
      switch (field) {
        case 'location':
          _locationKeyboardVisible = visible;
          break;
        case 'item':
          _itemKeyboardVisible = visible;
          break;
        case 'lpn':
          _lpnKeyboardVisible = visible;
          break;
        case 'qty':
          _qtyKeyboardVisible = visible;
          break;
      }
    });
  }

  // 重置所有输入框的键盘状态
  void _resetAllKeyboards() {
    if (_currentFocusField == null && !_locationKeyboardVisible && !_itemKeyboardVisible && !_lpnKeyboardVisible && !_qtyKeyboardVisible) {
      return;
    }
    setState(() {
      _locationKeyboardVisible = false;
      _itemKeyboardVisible = false;
      _lpnKeyboardVisible = false;
      _qtyKeyboardVisible = false;
      _currentFocusField = null;
    });
    FocusScope.of(context).unfocus();
    _hideKeyboard();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final authService = Provider.of<AuthService>(context);
    warehouseId = authService.currentUser?.warehouse;
    userId = authService.currentUser?.userId;
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _locationFocusNode.removeListener(() => _handleFocusChange('location', _locationFocusNode));
    _itemFocusNode.removeListener(() => _handleFocusChange('item', _itemFocusNode));
    _lpnFocusNode.removeListener(() => _handleFocusChange('lpn', _lpnFocusNode));
    _qtyFocusNode.removeListener(() => _handleFocusChange('qty', _qtyFocusNode));
    
    _itemFocusNode.dispose();
    _lpnFocusNode.dispose();
    _qtyFocusNode.dispose();
    _locationFocusNode.dispose();
    _itemNumberController.dispose();
    _lpnController.dispose();
    _qtyController.dispose();
    _locationController.dispose();
    super.dispose();
  }

  // 导航到putaway detail
  void _navigativePutawayDetail() async{
    _resetAllKeyboards();
    
    try{
      if(loadId == null){
        MessageBox.showMessageBox(context,'Unkown error, please contact with your system admin.',isError:true);
        return;
      }
      final responseData = await _fetchPutawayDetailData(loadId);
      if(responseData['code'] == 2000){
        Navigator.pushNamed(
          context,
          '/inbound/putaway-detail',
          arguments: {
            'loadNumber':loadNumber,
            'loadId':loadId,
          },
        );
      }
    }
    catch(e){
      Navigator.pop(context);
      MessageBox.showMessageBox(context,e,isError:true);
    }
  }

  // 调用接口获取渲染putaway detail页面的数据
  Future<Map<dynamic,dynamic>> _fetchPutawayDetailData(int? id) async{
    final apiUrl = ApiService.baseURL + ApiService.fetchPutawayDetail;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      print('url---:$apiUrl$id');
      final response = await http.get(
        Uri.parse('$apiUrl$id'),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
      );
      if(response.statusCode == 200){
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('jsonData---:${jsonData}');
        if (jsonData['code'] == 2000) {
          return jsonData;
        }
        else if(jsonData['code'] == 401){
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('The session has expired, Please log in again.');
        }
        else {
          throw Exception('${jsonData['msg']}');
        }
      }
      else{
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  // 点击Next按钮
  void _handleSubmitt() async{
    _resetAllKeyboards();
    
    try{
      if(!_scannedData){
        MessageBox.showMessageBox(context,'Please scan QR code.',isError:true);
        return;
      }
      if(_itemNumberController.text.isEmpty){
        MessageBox.showMessageBox(context,'Please enter item.',isError:true);
        return;
      }
      else{
        if(!_isValidManualInput(_itemNumberController.text)){
          MessageBox.showMessageBox(context,'Item: Incorrect format, please check again.',isError:true);
          return;
        }
      }
      if(_locationController.text.isEmpty){
        MessageBox.showMessageBox(context,'Please enter location.',isError:true);
        return;
      }

      if(_qtyController.text.isEmpty){
        MessageBox.showMessageBox(context,'Please enter quantity.',isError:true);
        return;
      }

      final response = await _createPutawayTask();
      print('response----${response}');
      if(response['code'] == 2000) {
        MessageBox.showMessageBox(context,response['msg'],isError:false);
        setState((){
          _itemNumberController.clear();
          _lpnController.clear();
          _qtyController.clear();
          _locationController.clear();
          _scannedData = false;
          helpText = '';
          totalQuantity = null;
          internalItemNumber = null;
          packKey = null;
          // 重置后重新聚焦到Location（不弹键盘）
          Future.delayed(const Duration(milliseconds: 100), () {
            if (mounted) _focusOnField('location', showKeyboard: false);
          });
          remainingQty = response['data']['load_remaining_qty'];
          print('remainingQty1----${remainingQty}');
        });
      }
      else{
        MessageBox.showMessageBox(context,response['msg'],isError:true);
        // 错误后重新聚焦到Location（不弹键盘）
        Future.delayed(const Duration(milliseconds: 100), () {
          if (mounted) _focusOnField('location', showKeyboard: false);
        });
      }
      
      print('remainingQty2----${remainingQty}');
      if(remainingQty != null && remainingQty == 0){
        // 先显示消息弹窗，用户确认后再跳转
        await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text(
                response['code'] == 2000 ? 'Success' : 'Error',
                style: TextStyle(
                  fontSize: 18 * _fontScale, 
                  color: response['code'] == 2000 
                      ? const Color.fromARGB(255, 4, 170, 10) 
                      : const Color.fromARGB(255, 255, 17, 0)
                ),
              ),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    Text(response['msg']),
                  ],
                ),
              ),
              actions: <Widget>[
                TextButton(
                  child: const Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop(); // 关闭弹窗
                  },
                ),
              ],
            );
          },
        );
        Navigator.pushNamed(
          context,
          '/inbound/putaway-detail',
          arguments: {
            'loadNumber':loadNumber,
            'loadId':loadId,
          },
        );
      }
    }
    catch(e){
      MessageBox.showMessageBox(context,e,isError:true);
      // 异常后重新聚焦到Location（不弹键盘）
      Future.delayed(const Duration(milliseconds: 100), () {
        if (mounted) _focusOnField('location', showKeyboard: false);
      });
    }
  }

  Future<Map<dynamic,dynamic>> _createPutawayTask() async {
    final apiUrl = ApiService.baseURL + ApiService.createPutawayTask;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      
      var requestBody = {
        'load': loadId,
        'putaway_task':{
          'location': _locationController.text,
          'warehouse': warehouseId,
          'item_number': itemNumber,
          'pack_key': packKey,
          'assigned_to': userId,
          'status': 'In Progress',
          'quantity': int.parse(_qtyController.text),
          'internal_item_number':internalItemNumber
        },
      };
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
        body: jsonEncode(requestBody),
      );
      print('apiUrl---:$apiUrl');
      print('requestBody---:$requestBody');
      if(response.statusCode == 200){
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('jsonData-_createPutawayTask--:${jsonData}');
        if (jsonData['code'] == 2000) {
          return jsonData;
        }
        else if(jsonData['code'] == 401){
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('The session has expired, Please log in again.');
        }
        else {
          throw Exception('${jsonData['msg']}');
        }
      }
      else{
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  // 处理Item输入（扫描或手动输入）
  void _handleItemInput(String value) {
    value = value.trim();
    if (value.isEmpty) return;

    // 尝试解析JSON（扫描枪输入）
    try {
        oldItemNumber = itemNumber;
        itemNumber = Utils.parseQRCode(value,'item number');
        lpnNumber = Utils.parseQRCode(value,'lpn number');
        packKey = Utils.parseQRCode(value,'pack key');
        orderNumber = Utils.parseQRCode(value,'order number');
        internalItemNumber = Utils.parseQRCode(value,'product code');
        _scannedData = true;
        
        if (itemNumber != null) {
          _itemNumberController.text = packKey.toString();
        }
        if (lpnNumber != null) {
          _lpnController.text = lpnNumber.toString();
        }
        
        // 解析后聚焦到Item输入框（不弹键盘）
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            _focusOnField('item', showKeyboard: false);
            // 选中Item输入框文本
            if (_itemNumberController.text.isNotEmpty) {
              _itemNumberController.selection = TextSelection(
                baseOffset: 0,
                extentOffset: _itemNumberController.text.length,
              );
            }
          }
        });
        
        _fetchItemData();
    } catch (e) {
      MessageBox.showMessageBox(context, e,isError: true);
    }
  }

  // 校验手动输入格式
  bool _isValidManualInput(String value) {
    final parts = value.split('--');
    return parts.length == 3 && 
           parts[0].isNotEmpty && 
           parts[1].isNotEmpty && 
           int.tryParse(parts[2]) != null;
  }

  // 调用API获取数据
  Future<void> _fetchItemData() async {
    if (!_scannedData) {
      MessageBox.showMessageBox(context,'Please scan the QR code.',isError:true);
      return;
    }

    if (orderNumber == null) {
      MessageBox.showMessageBox(context,'Invaild QR code.',isError:true);
      return;
    }

    try {
      Map<String, dynamic> responseData = await _fetchQuantity();
      
      if (responseData['code'] == 2000) {
        final data = responseData['data'] as Map<String, dynamic>;
        setState(() {
          totalAdded = data['need_task_qty']?.toString()??'0';
          helpText = '0 - $totalAdded';
          totalQuantity = data['load_line_qty']?.toString()??'';
          var quantity = 1;
          if (_qtyController.text.isNotEmpty && oldItemNumber == itemNumber) {
            if(int.parse(_qtyController.text) < int.parse(totalAdded)){
              quantity += int.parse(_qtyController.text);
            }
            else{
              quantity = int.parse(_qtyController.text);
            }
          }
          _qtyController.text = quantity.toString();
        });
        // 聚焦到Quantity输入框（不弹键盘）
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            _focusOnField('qty', showKeyboard: false);
            if (_qtyController.text.isNotEmpty) {
              _qtyController.selection = TextSelection(
                baseOffset: 0,
                extentOffset: _qtyController.text.length,
              );
            }
          }
        });
      } else {
        MessageBox.showMessageBox(context,responseData['msg'],isError:true);
      }
    } catch (e) {
      MessageBox.showMessageBox(context,e,isError:true);
    }
  }

  // 调用获取数量的API
  Future<Map<String,dynamic>> _fetchQuantity() async {
    final apiUrl = '${ApiService.baseURL}${ApiService.fetchQuantity}load=$loadId&pack_key=$packKey';
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      print('apiUrl---$apiUrl');
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
      );
      if(response.statusCode == 200){
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('jsonData---:${jsonData}');
        if (jsonData['code'] == 2000) {
          return jsonData;
        }
        else if(jsonData['code'] == 401){
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('The session has expired, Please log in again.');
        }
        else {
          throw Exception('${jsonData['msg']}');
        }
      }
      else{
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  // 通用输入框组件（关键修复4：禁用输入框默认的键盘触发）
  Widget _buildInputField({
    required String label,
    required TextEditingController controller,
    required FocusNode focusNode,
    required String field, // location/item/lpn/qty
    required TextInputType keyboardType,
    List<TextInputFormatter>? inputFormatters,
    bool readOnly = false,
    String? hintText,
    VoidCallback? onTap,
    ValueChanged<String>? onSubmitted,
    ValueChanged<String>? onChanged,
  }) {
    final isSmallScreen = MediaQuery.of(context).size.width < 360;
    return SizedBox(
      height: 30,
      child: Row(
        children: [
          SizedBox(
            width: 100,
            child: Text('$label:', style: TextStyle(fontSize: labelFontSize * _fontScale)),
          ),
          const SizedBox(width: 5),
          Expanded(
            child: TextField(
              readOnly: readOnly,
              controller: controller,
              focusNode: focusNode,
              keyboardType: keyboardType,
              inputFormatters: inputFormatters,
              // 关键修复：禁用输入框的默认键盘唤起（仅通过手动触发）
              enableInteractiveSelection: true, // 允许选中文本
              onTapOutside: (event) {
                // 点击输入框外部时，隐藏键盘
                _hideKeyboardForField(field);
                _unfocusField(field);
              },
              decoration: InputDecoration(
                border: const OutlineInputBorder(),
                contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                hintText: hintText,
                hintStyle: TextStyle(fontSize: textFontSize * _fontScale),
                // 键盘控制图标（默认收起状态）
                suffixIcon: IconButton(
                  icon: Icon(
                    _getKeyboardState(field) ? Icons.keyboard_hide : Icons.keyboard,
                    color: const Color(0xFF008363),
                    size: isSmallScreen ? 18 : 20,
                  ),
                  onPressed: () => _toggleKeyboardForField(field),
                  splashRadius: 20,
                  padding: const EdgeInsets.all(4),
                  constraints: const BoxConstraints.tightFor(width: 36, height: 36),
                ),
              ),
              style: TextStyle(fontSize: textFontSize * _fontScale),
              onTap: () {
                // 点击输入框：聚焦并弹出键盘（核心交互）
                _focusOnField(field, showKeyboard: true);
                // 选中全部文本
                if (controller.text.isNotEmpty) {
                  controller.selection = TextSelection(
                    baseOffset: 0,
                    extentOffset: controller.text.length,
                  );
                }
                if (onTap != null) onTap();
              },
              onSubmitted: onSubmitted,
              onChanged: onChanged,
            ),
          ),
          // Quantity输入框右侧的数量提示
          if (field == 'qty' && totalQuantity != null)
            Padding(
              padding: const EdgeInsets.only(left: 8),
              child: Text(
                ' /$totalAdded / $totalQuantity',
                style: TextStyle(fontSize: textFontSize * _fontScale),
              ),
            ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    userId = user?.userId;
    final mediaQuery = MediaQuery.of(context);
    final isSmallScreen = mediaQuery.size.width < 360;

    return Scaffold(
      appBar: AppBar(
        title: Text('Putaway Tasks', style: TextStyle(fontSize: 18 * _fontScale)),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            _resetAllKeyboards();
            Navigator.pushNamed(
              context,
              '/inbound/putaway-summary',
              arguments: {
                'loadNumber':loadNumber,
                'loadId':loadId,
              },
            );
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () {
              _resetAllKeyboards();
              Navigator.pushNamed(context, '/home');
            },
          ),
        ],
        backgroundColor: const Color(0xFF008363),
      ),
      // 关键修复5：确保页面不随键盘调整，避免间接触发键盘
      resizeToAvoidBottomInset: false,
      body: GestureDetector(
        onTap: () => _resetAllKeyboards(),
        behavior: HitTestBehavior.opaque,
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : Stack(
                children: [
                  // 可滚动内容区
                  Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: _bottomButtonAreaHeight,
                    child: SingleChildScrollView(
                      padding: EdgeInsets.symmetric(
                        vertical: 10, 
                        horizontal: isSmallScreen ? 16 : 32
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // Location输入行
                          _buildInputField(
                            label: 'Location',
                            controller: _locationController,
                            focusNode: _locationFocusNode,
                            field: 'location',
                            keyboardType: TextInputType.text,
                            onSubmitted: (_) => _focusOnField('item', showKeyboard: false),
                          ),
                          const SizedBox(height: 10),
                          // Item输入行
                          _buildInputField(
                            label: 'Item',
                            controller: _itemNumberController,
                            focusNode: _itemFocusNode,
                            field: 'item',
                            keyboardType: TextInputType.none, // 扫描专用，禁用系统键盘
                            onSubmitted: _handleItemInput,
                            onChanged: (value) {
                              if (_itemFocusNode.hasFocus) {
                                _itemNumberController.selection = TextSelection(
                                  baseOffset: 0,
                                  extentOffset: value.length,
                                );
                              }
                            },
                          ),
                          const SizedBox(height: 10),
                          // LPN#输入行
                          _buildInputField(
                            label: 'LPN#',
                            controller: _lpnController,
                            focusNode: _lpnFocusNode,
                            field: 'lpn',
                            keyboardType: TextInputType.text,
                            onSubmitted: (_) => _focusOnField('qty', showKeyboard: false),
                          ),
                          const SizedBox(height: 10),
                          // Quantity输入行
                          _buildInputField(
                            label: 'Quantity',
                            controller: _qtyController,
                            focusNode: _qtyFocusNode,
                            field: 'qty',
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                              RangeInputFormatter(int.tryParse(totalAdded) ?? 0)
                            ],
                            hintText: helpText,
                            onSubmitted:(value) {
                              FocusScope.of(context).unfocus();
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                  
                  // 固定在底部的按钮区
                  Positioned(
                    bottom: 20,
                    left: 32,
                    right: 32,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        // Next按钮
                        SizedBox(
                          width: double.infinity,
                          height: 30,
                          child: ElevatedButton(
                            onPressed: hideNextButton ? _handleSubmitt : null,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: const Color(0xFF008363),
                              padding: EdgeInsets.symmetric(vertical: 8 * _fontScale),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                            ),
                            child: Text('Next', 
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: buttonFontSize * _fontScale,
                                color: Colors.white
                              )),
                          ),
                        ),
                        const SizedBox(height: 10),
                        // Putaway Detail按钮
                        SizedBox(
                          width: double.infinity,
                          height: 30,
                          child: ElevatedButton(
                            onPressed: _navigativePutawayDetail,
                            style: ElevatedButton.styleFrom(
                                backgroundColor: const Color(0xFF008363),
                                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8.0),
                                ),
                              ),
                            child: Text('Putaway Detail', style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: buttonFontSize * _fontScale,
                              color: Colors.white
                            )),
                          ),
                        ),
                        const SizedBox(height: 10),
                        // Exception按钮
                        SizedBox(
                          width: double.infinity,
                          height: 30,
                          child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.orange,
                              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                            ),
                            onPressed: () {
                              _resetAllKeyboards();
                              // MessageBox.showMessageBox(context, 'The functions need to be improved.', isError: true);
                            },
                            child: Text('Exception', style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: buttonFontSize * _fontScale,
                              color: Colors.white
                            )),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
      ),
    );
  }
}